<script setup>
import { ref, onMounted } from 'vue';
import { getAllHospitalsService, getDepartmentsByHospitalIdService, getClinicsByDepartmentIdService, getDoctorsByClinicIdService } from '@/api/hospital.js';
import { addAppointment } from '@/api/appointment.js'
import { ElMessage } from 'element-plus';
import { useUserInfoStore } from '@/stores/userInfo.js';
import { userInfoGetService } from '@/api/user.js';
import { getAllPatientsService } from '@/api/admin.js';
import { getAllSchedulesService } from '@/api/admin.js';
const userInfoStore = useUserInfoStore();
//获取个人信息
const getUserInfo = async () => {
    let result = await userInfoGetService();
    //存储pinia
    userInfoStore.setInfo(result.data);
}

console.log(userInfoStore.info);
// 定义医院、科室、诊所和医生数据
const hospitals = ref([]);
const departments = ref({});
const clinics = ref({});
const doctors = ref({});
const appointmentList = ref({
    doctorId: null,
    patientId: null,
    appointmentTime: null
})
const schedules = ref([]);
//获取所有的排班信息
const getAllSchedules = async () => {
    let result = await getAllSchedulesService(appointmentList.value.appointmentTime);
    schedules.value = result.data;
}
//console.log(appointmentList.value);
//获取所有的患者信息，通过username匹配获取PatientId
const getAllPatients = async () => {
    let result = await getAllPatientsService();
    for (const patient of result.data) {
        if (patient.username === userInfoStore.info.username) {
            appointmentList.value.patientId = patient.patientId;
        }
    }
}
// 获取所有医院信息的函数
const fetchHospitals = async () => {
    try {
        const response = await getAllHospitalsService();
        if (response.code === 0) {
            hospitals.value = response.data;
            // 自动加载科室
            for (const hospital of response.data) {
                await fetchDepartments(hospital.hospitalId);
            }
        } else {
            ElMessage.error(response.message || '获取医院信息失败');
        }
    } catch (error) {
        ElMessage.error('获取医院信息失败');
    }
};

// 获取科室信息
const fetchDepartments = async (hospitalId) => {
    try {
        const response = await getDepartmentsByHospitalIdService(hospitalId);
        if (response.code === 0) {
            departments.value[hospitalId] = response.data;
            // 自动加载诊所
            for (const department of response.data) {
                await fetchClinics(department.departmentId);
            }
        } else {
            ElMessage.error(response.message || '获取科室信息失败');
        }
    } catch (error) {
        ElMessage.error('获取科室信息失败');
    }
};

// 获取诊所信息
const fetchClinics = async (departmentId) => {
    try {
        const response = await getClinicsByDepartmentIdService(departmentId);
        if (response.code === 0) {
            clinics.value[departmentId] = response.data;
            // 自动加载医生
            for (const clinic of response.data) {
                await fetchDoctors(clinic.clinicId);
            }
        } else {
            ElMessage.error(response.message || '获取诊所信息失败');
        }
    } catch (error) {
        ElMessage.error('获取诊所信息失败');
    }
};

// 获取医生信息
const fetchDoctors = async (clinicId) => {
    try {
        const response = await getDoctorsByClinicIdService(clinicId);
        if (response.code === 0) {
            doctors.value[clinicId] = response.data;
        } else {
            ElMessage.error(response.message || '获取医生信息失败');
        }
    } catch (error) {
        ElMessage.error('获取医生信息失败');
    }
};
//增加预约信息
const addAppointmentService = async (row) => {
    appointmentList.value.doctorId = row.doctorId;
    if(appointmentList.value.appointmentTime){
        let result = await addAppointment(appointmentList.value);
        console.log(result);
        if(result.code===0){
            ElMessage.success("预约挂号成功");
        }else if(result.code===1){
            ElMessage.error(result.message?result.message:"预约挂号失败");
        }
    }else{
        ElMessage.error("请选择预约日期");
    }
}

// 在组件挂载时获取医院数据
onMounted(() => {
    getAllSchedules();
    fetchHospitals();
    getUserInfo();
    getAllPatients();
});
</script>

<template>
    <el-collapse>
        <el-date-picker
            v-model="appointmentList.appointmentTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择预约日期"
            style="margin-bottom: 20px;"
        ></el-date-picker>
        <el-collapse-item v-for="hospital in hospitals" :key="hospital.hospitalId"
            :name="hospital.hospitalId.toString()">
            <template #title>
                {{ hospital.hospitalName || '医院名称未提供' }} <!-- 显示医院名称 -->
            </template>
            <el-collapse>
                <el-collapse-item v-for="department in departments[hospital.hospitalId] || []"
                    :key="department.departmentId" :name="department.departmentId.toString()">
                    <template #title>
                        {{ department.departmentName || '科室名称未提供' }} <!-- 显示科室名称 -->
                    </template>
                    <el-collapse>
                        <el-collapse-item v-for="clinic in clinics[department.departmentId] || []"
                            :key="clinic.clinicId" :name="clinic.clinicId.toString()">
                            <template #title>
                                {{ clinic.clinicName || '诊所名称未提供' }} <!-- 显示诊所名称 -->
                            </template>
                            <el-table :data="doctors[clinic.clinicId] || []" style="width: 100%">
                                <el-table-column prop="name" label="医生姓名" width="150"></el-table-column>
                                <el-table-column prop="gender" label="性别" width="100"></el-table-column>
                                <el-table-column prop="username" label="用户名" width="150"></el-table-column>
                                <el-table-column prop="contactNumber" label="联系电话" width="150"></el-table-column>
                                <el-table-column prop="title" label="职称" width="150"></el-table-column>
                                <el-table-column label="操作" width="180">
                                    <template #default="scope">
                                        <el-button size="mini" type="primary"
                                            @click="addAppointmentService(scope.row)">预约挂号</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-collapse-item>
                    </el-collapse>
                </el-collapse-item>
            </el-collapse>
        </el-collapse-item>
    </el-collapse>
</template>

<style scoped>
/* 添加样式 */
</style>